import random
import time
import tinify
import paramiko

from requests import get
from json import loads
from math import ceil

COMPRESSIONS_MAX = 500


def get_image(min_size, max_size, zip_flag="false"):
    resp = get(
        f'https://www.hzhtyl.com/aed/getBigFiles?minSize={min_size}&maxSize={max_size}&maxLength=&sourceFlag=&zipFlag={zip_flag}')
    resp_con = loads(resp.content)
    total = int(resp_con.get('total', '0'))
    print(f'min_size:{min_size},max_size:{max_size},zip_flag:{zip_flag},total:{total}')
    return total


# 循环思路
# 1、开始通过min和max得到区间数量
# 2、区间数量小于100
# 3、则返回max
# 2、区间数量大于100，开启循环
# 3、按(max-min)/100 步长得到新的min和max区间，min不变max等于min+步长
# 4、重复步骤1、2、3，将返回的max赋值给min继续调用

def get_loop(obj):
    page_size = 50
    min_size = obj.get('min', 400)
    max_size = obj.get('max', 1424)
    total = get_image(min_size, max_size)
    if total <= page_size:
        get_image(min_size, max_size, 'true')
        status = True
        while status:
            time.sleep(30 + random.randint(15, 30))
            resp = get('https://www.hzhtyl.com/aed/getBigFilesStatus')
            resp_con = loads(resp.content)
            if resp_con.get('error_info', '') == 'UnfinishedWork:0':
                status = False
        return max_size
    else:
        pre = total / page_size
        index = ceil((max_size - min_size) / ceil(pre))
        while min_size < (max_size + index):
            min_size = get_loop({"min": min_size, "max": (min_size + index)})
        return min_size
    pass


def menu_input():
    min_size = input("请输入最小文件大小KB：")
    if not min_size:
        return menu_input()
    else:
        min_size = int(min_size)
    max_size = input("请输入最大文件大小KB（默认最小大小加1024KB）：")
    if not max_size:
        max_size = int(min_size) + 1024
    else:
        max_size = int(max_size)
    return {
        "min": min_size,
        "max": max_size,
    }


def load_tinify_keys(path: str):
    with open(path, mode='r', encoding='utf-8') as file:
        tinify_keys = file.readlines()
    return tinify_keys


if __name__ == '__main__':
    # inputLimit = menu_input()
    # get_loop(inputLimit)
    # print(inputLimit)
    try:
        ssh = paramiko.SSHClient()
        sftp = ssh.open_sftp()
        # keys = load_tinify_keys('./tinify_key.txt')
        # for key in keys:
        #     tinify.key = key.rstrip()
        #     tinify.validate()
        #     compressions_this_month = tinify.compression_count
        #     if compressions_this_month < COMPRESSIONS_MAX:
        #         print(compressions_this_month)
        #         # source = tinify.from_url("https://www.hzhtyl.com/aed/6f1e401307864c7dba6af84839745903.JPG")
        #         # source.to_file("6f1e401307864c7dba6af84839745903.JPG")

    except tinify.Error as e:
        pass
    pass
